package com.ziroom.finance.rabbitmq.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 短信工具类
 *
 * @author
 */
@SuppressWarnings("deprecation")
public class SMSUtils {

    private static final Logger logger = LoggerFactory.getLogger(SMSUtils.class);

    public static final String SMS_SWITCH_CLOSE_MSG = "fail:短信开关已关闭";

    // 2015-11-13新短信平台信息
    // 接口地址
    private static String smsUrl;
    // 有效认证
    private static String smsToken;
    // 短信开关
    private static String smsIsSend;

    static {
        if (smsUrl == null) {
            smsUrl = PropertiesUtil.getPropValAsString("zra.smsUrlNew");
            smsToken = PropertiesUtil.getPropValAsString("zra.smsToken");
            smsIsSend = PropertiesUtil.getPropValAsString("zra.smsIsSend");
        }
    }

    /**
     * 发送短信接口
     *
     * @param phone 手机号 多个情况用,分开
     * @param smg   短信内容
     * @return 异常返回：-100 开关未开启返回：fail:短信开关已关闭 0 成功 其余返回失败原因代码
     * API接口说明：https://code.ziroom.com/tech-docs/manual/blob/master/message/API.md
     */
    public static String noteSend(String phone, String smg) {
        if ("false".equals(smsIsSend)) {
            return SMS_SWITCH_CLOSE_MSG;
        }
        String send = "";
        try {
            JSONObject param = new JSONObject();
            // 认证标志
            param.put("token", smsToken);
            // 手机号
            param.put("to", phone);
            // 短信内容
            param.put("content", smg);
            JSONObject retJsonObj = doPost(smsUrl, param);
            send = isContainsKeyFromJson("response_code", retJsonObj) ? retJsonObj
                    .getString("response_code") : "";
            // 当返回值不为0时 说明失败了 获取返回json中的失败原因
            if (!"0".equals(send)) {
                send = isContainsKeyFromJson("error_info",
                        retJsonObj) ? retJsonObj.getString("error_info") : "";
            }
        } catch (Exception e) {
            logger.error("发送短信异常！", e);
            send = "-100";
        }
        logger.info("发送短信返回状态.." + send);
        return send;
    }

    /**
     * post接口地址 提交字符串
     *
     * @param url
     * @param json
     * @return
     */
    @SuppressWarnings("resource")
    public static JSONObject doPost(String url, JSONObject json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = new JSONObject();
        try {
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");// 发送json数据需要设置contentType
            post.setHeader("Content-Type", "text/html;charset=UTF-8");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.parseObject(result);
            } else {
                logger.error("发送短信请求异常...StatusCode==" + res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.error("发送短信请求异常。", e);
            throw new RuntimeException(e);
        } finally {
            client.close();
            client = null;
        }
        return response;
    }


    /**
     * 判断JSONObject中是否存在指定的key
     *
     * @param key
     * @param obj
     * @return
     */
    public static boolean isContainsKeyFromJson(String key, JSONObject obj) {

        if (obj.containsKey(key)) {
            return true;
        } else {
            return false;
        }

    }


}
